package com.hasnext.tool.poi;

import com.hasnext.tool.bean.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class Words {

    static final String template = "src/main/resources/templates/sample.docx";

    public void createWord(UserInfo user, File save) throws IOException {

        Map<String, String> textMap = new HashMap<>();

        textMap.put("${name}", user.getName());

        textMap.put("${sex}", user.getSex());

        XWPFDocument document = new XWPFDocument(new FileInputStream(new File(template)));

        setParagraphs(textMap, document.getParagraphs());

        setTables(textMap, document);

        try (FileOutputStream outputStream = new FileOutputStream(save)) {

            document.write(outputStream);

        }

    }

    /**
     * 设置表格
     *
     * @param textMap
     * @param document
     */
    public void setTables(Map<String, String> textMap, XWPFDocument document) {

        List<XWPFTable> tables = document.getTables();

        tables.forEach(table -> {

            List<XWPFTableRow> rows = table.getRows();

            rows.forEach(row -> {

                List<XWPFTableCell> cells = row.getTableCells();

                cells.forEach(cell -> {

                    setParagraphs(textMap, cell.getParagraphs());

                });

            });

        });

    }

    /**
     * 设置段落
     *
     * @param textMap
     * @param paragraphs
     */
    public void setParagraphs(Map<String, String> textMap, List<XWPFParagraph> paragraphs) {

        paragraphs.forEach(paragraph -> {

            if (!paragraph.getText().contains("$")) {

                return;

            }

            List<XWPFRun> runs = paragraph.getRuns();

            runs.forEach(run -> {

                String value = run.getText(run.getTextPosition());

                for (Map.Entry<String, String> entry : textMap.entrySet()) {

                    value = value.replace(entry.getKey(), entry.getValue());

                }

                run.setText(value, 0);

            });

        });

    }


    public List<String> getFieldName(Object object) {

        Field[] field = object.getClass().getDeclaredFields();

        List<String> fields = Arrays.stream(field).map(Field::getName).collect(Collectors.toList());

        return fields;

    }


}
